package cn.wolfcode.interceptor;

import cn.wolfcode.annotation.RequireLogin;
import cn.wolfcode.entity.Userinfo;
import cn.wolfcode.redis.service.IUserInfoRedisService;
import cn.wolfcode.util.JSONResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    IUserInfoRedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // crossorigin
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        boolean has = handlerMethod.hasMethodAnnotation(RequireLogin.class);
        if (has) {
            String token = request.getHeader("token");
            Userinfo user = redisService.getUserByToken(token);
            if (user == null) {
                response.setContentType("application/json;charset=utf-8");
                JSONResult error = JSONResult.noLoginError();
                response.getWriter().write(JSON.toJSONString(error));
                return false;
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
